package judesart.app.client.ui.admin.profile;

import gwtupload.client.IUploader;
import gwtupload.client.MultiUploader;
import gwtupload.client.IFileInput.AnchorFileInput;
import gwtupload.client.IUploader.OnFinishUploaderHandler;
import gwtupload.client.IUploader.OnStartUploaderHandler;

import java.util.ArrayList;
import java.util.List;

import judesart.app.client.controller.ExhibitionController;
import judesart.app.client.controller.ExhibitionControllerAsync;
import judesart.app.client.widget.TopInfo;
import judesart.app.domain.Exhibition;
import judesart.app.domain.ExhibitionPhoto;

import com.allen_sauer.gwt.log.client.Log;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelReader;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.MemoryProxy;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.Composite;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.ListView;
import com.google.appengine.api.datastore.Text;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class ExhibitionPhotosPanel extends Composite {

    ExhibitionControllerAsync service = ExhibitionController.Util.getInstance();

    private final ExhibitionDetailPanel parent;
    private final BaseListLoader<ListLoadResult<ExhibitionPhoto>> loader;
    private final List<ExhibitionPhoto> photos = new ArrayList<ExhibitionPhoto>();

    private final LayoutContainer layoutContainer;

    public ExhibitionPhotosPanel(ExhibitionDetailPanel parent) {
        this.parent = parent;

        layoutContainer = new LayoutContainer();
        layoutContainer.setSize(798, 450);
        layoutContainer.setBorders(false);
        layoutContainer.setScrollMode(Scroll.AUTO);

        MemoryProxy<List<ExhibitionPhoto>> proxy = new MemoryProxy<List<ExhibitionPhoto>>(photos);

        loader = new BaseListLoader<ListLoadResult<ExhibitionPhoto>>(proxy, new BeanModelReader());
        ListStore<BeanModel> store = new ListStore<BeanModel>(loader);
        loader.load();

        final ListView<BeanModel> listView = new ListView<BeanModel>(store);
        listView.setLoadingText("loading...");
        listView.setBorders(false);
        listView.setTemplate(getTemplate());
        listView.setItemSelector("div.thumb-wrap");
        listView.getSelectionModel().addListener(Events.SelectionChange,
                new Listener<SelectionChangedEvent<BeanModel>>() {
                    public void handleEvent(SelectionChangedEvent<BeanModel> be) {
                        // onSelectionChanged(be);
                    }
                });

        layoutContainer.add(listView);

        MultiUploader defaultUploader = new MultiUploader();

        defaultUploader.addOnFinishUploadHandler(new OnFinishUploaderHandler() {

            @Override
            public void onFinish(IUploader uploader) {
                uploadFinished(uploader);
            }
        });
        defaultUploader.setMaximumFiles(10);
        defaultUploader.setFileInputPrefix("default");
        defaultUploader.avoidRepeatFiles(true);
        defaultUploader.setFileInput(new AnchorFileInput());
        defaultUploader.addOnStartUploadHandler(new OnStartUploaderHandler() {
            @Override
            public void onStart(IUploader uploader) {
                uploader.setServletPath("/upload");
            }
        });

        layoutContainer.add(defaultUploader);

        initComponent(layoutContainer);
    }

    protected void refresh() {
        photos.clear();
        Exhibition exhibition = getParentPanel().getExhibition();
        if (exhibition != null && exhibition.getPhotos() != null
                && exhibition.getPhotos().size() > 0) {
            photos.addAll(exhibition.getPhotos());
        }
        loader.load();
        layoutContainer.layout();
    }

    private void addPhotoToPanel(String imageId) {
        Log.debug("addPhotoToPanel -> imageId [" + imageId + "]");
        final ExhibitionPhoto data = new ExhibitionPhoto();
        data.setImageId(new Long(imageId));
        service.findPhotoKeyByImageId(data.getImageId(),
                new AsyncCallback<String>() {
                    @Override
                    public void onFailure(Throwable caught) {
                        Log.error("Unable to get sketch key fo image.", caught);
                    }

                    @Override
                    public void onSuccess(String result) {
                        Log.debug(" got key for image [" + result + "]");
                        data.setKey(result);
                    }
                });
        data.setImageId(new Long(imageId));
        data.setDescription(new Text(""));
        photos.add(data);
        loader.load();
        layoutContainer.layout();
    }

    private native String getTemplate() /*-{
        return ['<tpl for=".">', 
        '<div style="border: 1px solid #FFFFFF;float:left;margin:4px 0 4px  4px; padding:2px;width:124px; height: 140px;" class="thumb-wrap" id="{imageId}">', 
        '<div style="width: 120px;" class="thumb"><img src="/image?id={imageId}&size=120x120"></div>', 
        '<div style="width: 100%; text-align: center; color: #999999;">{description}</div>',
        '</div>',
        '</tpl>', 
        '<div class="x-clear"></div>'].join("");
    }-*/;

    private ExhibitionDetailPanel getParentPanel() {
        return parent;
    }

    private void uploadFinished(IUploader uploader) {
        TopInfo.display("Info", "Upload : " + uploader.getStatus().name());
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "/commitimages?action=addToExhibitionPhoto&exhibitionId="
                + getParentPanel().getExhibition().getId());
        try {
            builder.sendRequest(null, new RequestCallback() {

                @Override
                public void onResponseReceived(Request request,
                        Response response) {
                    Log.debug("onFinish -> " + response.getText());
                    addPhotoToPanel(response.getText());
                }

                @Override
                public void onError(Request request, Throwable exception) {
                    Log.error("Error sending commit request", exception);
                    TopInfo.display("Error", "Unable to add images");
                }
            });
        } catch (RequestException e) {
            Log.error("Error sending commit request", e);
            TopInfo.display("Error", "Unable to add images");
        }
    }
}
